/* Copyright (c) 2011-2012 ISP RAS, Moscow. For more information please write to
 
      mermakov@ispras.ru
      svartanov@ispras.ru

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package ru.ispras.coffeemachine.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Executor
 * 
 * @author Sergey Vartanov <me@enzet.ru>
 * @version 1.2.0
 * @since 2011-09-12
 */
public class Executor
{
	public static InputStream stream;
	public static InputStream errorStream;
	
	/**
	 * Process execution
	 * 
	 * @param command program name with command line parameters
	 */
	
	public static Output execute(String command)
	{
		return execute(command, null);
	}
	
	public static Output execute(String command, String dir)
	{
		File execDir = null;
		if (dir != null) {
			execDir = new File(dir);
		}
		Process process;
		try
		{
			if (execDir != null) {
				process = Runtime.getRuntime().exec(command, null, execDir);
			} else {
				process = Runtime.getRuntime().exec(command);
			}
			
			stream = process.getInputStream();
			errorStream = process.getErrorStream();
			
			byte b[] = new byte[1];
			String out = "";
			
			while (stream.read(b) != -1)
			{
				String n = new String(b);
				
				out += n;
				if (Options.printExec)
				{
					System.out.print(n);
				}
				
				b = new byte[1];
			}
			process.waitFor();
			
			return new Output(out, readStream(errorStream));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(0);
		}
		return null;
	}

	public static String readStream(InputStream in) throws IOException
	{
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[409600]; // FIXME
		for (int n; (n = in.read(b)) != -1;)
		{
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

	/**
	 * Get directory sequence from the path (path without file name)
	 */
	public static String getDirectory(String filePath)
	{
		if (filePath.contains("/"))
		{
			return filePath.substring(0, filePath.lastIndexOf('/'));
		}
		else return "";
	}

	/**
	 * Get pure file name without directory
	 */
	public static String trimDirectory(String filePath)
	{
		if (filePath.contains("/"))
		{
			return filePath.substring(filePath.lastIndexOf('/'), filePath.length());
		}
		else return filePath;
	}

	/**
	 * Make directory
	 */
	public static void makeDirectory(String directory)
	{
		int position = 0, slash;
		Output trace;

		while ((slash = directory.indexOf('/', position)) != -1)
		{
			trace = Executor.execute("mkdir " + directory.substring(0, slash));
			position = slash + 1;
		}
		trace = Executor.execute("mkdir " + directory);
		trace.checkErrors();
	}
}
